package com.server.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.server.common.base.PathManager;
import com.server.common.base.ProjectInfor;
import com.server.common.base.SessionData;
import com.server.service.ICourseStudyService;
import com.server.service.IExaminationService;
import com.server.web.DataVector;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;
import com.server.web.RequestInput;
import com.server.web.SessionUtil;


@Controller
@RequestMapping("study/course")
public class CourseStudyController {
	
	@Autowired
	private ICourseStudyService courseStudyService;
	@Autowired
	private IExaminationService examinationService;
	

	/**
	 * 课程列表
	 * @param request
	 * @param response
	 * @author ServerZhang
	 * @date 2016年8月5日
	 */
	@RequestMapping("pdf/{id}")
	public ModelAndView pdf(HttpServletRequest request ,
			HttpServletResponse response,@PathVariable Integer id ){
		ModelAndView mv = new ModelAndView("study/web/viewer1");
		//通过课程ID获取pdf的地址
		Map<String, Object> form = courseStudyService.getForm(request,id);
		StringBuffer pdfUrl = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		pdfUrl.append("http://").append(serverName)
			.append(":").append(serverPort).append("/")
			.append(PathManager.FILE_MAPPING).append(form.get("pptUrl"));
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		
		StringBuffer serverBuffer = new StringBuffer();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		
		//mv.addObject("fileServer",PathManager.FILE_SERVER_ATTR);
		mv.addObject("pdfUrl",pdfUrl);
		return mv;
	}
	@RequestMapping("VideoIframe/{id}")
	public ModelAndView VideoIframe(HttpServletRequest request,@PathVariable Integer id){
		ModelAndView mv = new ModelAndView("study/courseStudy/VideoIframe");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addAllObjects(courseStudyService.getForm(request,id));
		mv.addObject("url",  SessionUtil.getStringAttri(request, SessionData.photoUrlKey));
		mv.addObject("userName",SessionUtil.getStringAttri(request, SessionData.nameKey));
		mv.addObject("uuid",SessionUtil.getStringAttri(request, SessionData.uuidKey));
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		
		//mv.addObject("fileServer",PathManager.FILE_SERVER_ATTR);
		return mv;
	}
	@RequestMapping("")
	public ModelAndView course(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("study/courseStudy/homePage");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		
		//mv.addObject("fileServer",PathManager.FILE_SERVER_ATTR);
		return mv;
	}
	@RequestMapping("list")
	public void list(HttpServletRequest request,HttpServletResponse response){
		String whereStr = "state=5";
		DataVector<Map<String, Object>> listData = courseStudyService.getList(whereStr, null, new RequestInput(request));
		List<Map<String, Object>> list = listData.getList();
		Iterator<Map<String, Object>> iterator = list.iterator();
		while(iterator.hasNext()){
			Map<String, Object> next = iterator.next();
			//计算课程学习进度
			String nickname = SessionUtil.getStringAttri(request, SessionData.nameKey);
			if(StringUtils.isEmpty(nickname)){
				next.put("progress", 0);
			}else{
				Integer type = (Integer) next.get("type");
				Integer id =  (Integer) next.get("id");
				int progress=0;
				if(type==1){
					progress = courseStudyService.countProcess(id,nickname);
				}else{
					progress = courseStudyService.countProcess2(id, nickname);
				}
				 
				next.put("progress", progress);
			}
		}
		
		OutputUtil.returnGridData(response, listData.getCount(), JSONSerielizer.toJson(list, null, null));
	}
	 /**
	 * 课程详细
	 * @param request
	 * @param id
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月5日
	 */
	@RequestMapping("detail/{id}/{type}")
	public ModelAndView detail(HttpServletRequest request,HttpServletResponse response,
			@PathVariable Integer id,@PathVariable Integer type){
		//每进一次这个页面，课程点击数+1
		courseStudyService.click(id);
		
		ModelAndView mv = null;
		switch (type) {
		case 1:
			mv = new ModelAndView("study/courseStudy/Images_Text");
			break;
		case 2:
			mv = new ModelAndView("study/courseStudy/audio");
			break;
		case 3:
			mv = new ModelAndView("study/courseStudy/video");
			break;

		default:
			break;
		}
		mv.addAllObjects(courseStudyService.getForm(request,id));
		mv.addObject("url",  SessionUtil.getStringAttri(request, SessionData.photoUrlKey));
		mv.addObject("userName",SessionUtil.getStringAttri(request, SessionData.nameKey));
		mv.addObject("uuid",SessionUtil.getStringAttri(request, SessionData.uuidKey));
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		
		//mv.addObject("fileServer",PathManager.FILE_SERVER_ATTR);
		mv.addObject("type",type);
		return mv;
	}
	@RequestMapping("catalog/{id}")
	public void catalog(HttpServletRequest request,
			HttpServletResponse response,@PathVariable Integer id){
		List<Map<String, Object>> catalog = courseStudyService.getCatalog(id);
		OutputUtil.returnString(response, JSONSerielizer.toJson(catalog, null, null));
	}
	/**
	 * 已学习就获取学习进度，未学习就添加学习进度
	 * 
	 * @param request
	 * @param response
	 * @author xiaoxiaoping
	 * @date 2016年8月11日
	 */
	
	@RequestMapping("studyProcess")
	public void addStudy(HttpServletRequest request,
			HttpServletResponse response){
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Boolean isSuccess = true;
		String nickname = SessionUtil.getStringAttri(request, SessionData.nameKey);
		if(StringUtils.isEmpty(nickname)){
			isSuccess = false;
			returnMap.put("isSuccess", isSuccess);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}else{
			String courseId = request.getParameter("courseId");
			String fileId = request.getParameter("fileId");
			String listId = request.getParameter("listId");
			String totalTime = request.getParameter("totalTime");
			Map<String, Object> whereMap = new HashMap<String, Object>();
			whereMap.put("courseId", courseId);
			whereMap.put("fileId", fileId);
			if(!StringUtils.isEmpty(listId)){
				whereMap.put("listId", listId);
			}
			whereMap.put("creater", nickname);
			returnMap = courseStudyService.selectStudy(whereMap);
			if(returnMap == null || returnMap.size() <= 0){
				Map<String, Object> inputMap = new HashMap<String, Object>();
				//Map<String,Object> map = new HashMap<String, Object>();
				inputMap.put("courseId", courseId);
				inputMap.put("fileId", fileId);
				if(!StringUtils.isEmpty(listId)){
					inputMap.put("listId", listId);
				}
				inputMap.put("totalTime",totalTime );
				isSuccess = courseStudyService.studyProcess(inputMap, nickname);
				returnMap = new HashMap<String, Object>();
				returnMap.put("isSuccess", isSuccess);
				OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
			}else{
				OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
				
			}
		}
	}
	@RequestMapping("updatProcess")
	public void updateProcess(HttpServletRequest request,
			HttpServletResponse response){
		Map<String,Object> returnMap = new HashMap<String, Object>();
		Boolean isSuccess = true;
		String info = null;
		String nickname = SessionUtil.getStringAttri(request, SessionData.nameKey);
		if(StringUtils.isEmpty(nickname)){
			isSuccess = false;
			info = "请登录";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}else{
			String courseId = request.getParameter("courseId");
			String fileId = request.getParameter("fileId");
			String listId = request.getParameter("listId");
			String currentTime = request.getParameter("currentTime");
			Map<String, Object> whereMap = new HashMap<String, Object>();
			whereMap.put("courseId", courseId);
			whereMap.put("fileId", fileId);
			if(!StringUtils.isEmpty(listId)){
				whereMap.put("listId", listId);
			}
			whereMap.put("creater", nickname);
			Boolean state = courseStudyService.updateProcess(whereMap, currentTime);
			if(state){
				isSuccess = true;
				info = "保存成功";
			}else{
				isSuccess = false;
				info = "保存失败";
			}
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}
	}
	@RequestMapping("updatEndProcess")
	public void updateEndProcess(HttpServletRequest request,
			HttpServletResponse response){
		Map<String,Object> returnMap = new HashMap<String, Object>();
		Boolean isSuccess = true;
		String info = null;
		String nickname = SessionUtil.getStringAttri(request, SessionData.nameKey);
		if(StringUtils.isEmpty(nickname)){
			isSuccess = false;
			info = "请登录";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}else{
			String courseId = request.getParameter("courseId");
			String fileId = request.getParameter("fileId");
			String listId = request.getParameter("listId");
			Map<String, Object> whereMap = new HashMap<String, Object>();
			whereMap.put("courseId", courseId);
			whereMap.put("fileId", fileId);
			if(!StringUtils.isEmpty(listId)){
				whereMap.put("listId", listId);
			}
			whereMap.put("creater", nickname);
			Boolean state = courseStudyService.updateEndProcess(whereMap);
			if(state){
				isSuccess = true;
				info = "保存成功";
			}else{
				isSuccess = false;
				info = "保存失败";
			}
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}
	}
	/**
	 * 获取笔记，如果没有就新建
	 * 
	 * @param request
	 * @param response
	 * @author xiaoxiaoping
	 * @date 2016年8月11日
	 */
	@RequestMapping("getNotes")
	public void getNots(HttpServletRequest request,
			HttpServletResponse response){
		Map<String,Object> returnMap = new HashMap<String, Object>();
		Boolean isSuccess = true;
		String info = null;
		String nickname = SessionUtil.getStringAttri(request, SessionData.nameKey);
		if(StringUtils.isEmpty(nickname)){
			isSuccess = false;
			info = "请登录";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}else{
			String courseId = request.getParameter("courseId");
			String listId = request.getParameter("listId");
			Map<String, Object> whereMap = new HashMap<String, Object>();
			whereMap.put("courseId", courseId);
			whereMap.put("listId", listId);
			whereMap.put("creater", nickname);
			returnMap = courseStudyService.getNotes(whereMap);
			if(returnMap != null){
				OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
			}else{
				Map<String, Object> inputMap = new HashMap<String, Object>();
				Map<String,Object> map = new HashMap<String, Object>();
				inputMap.put("courseId", courseId);
				inputMap.put("listId", listId);
				Boolean state = courseStudyService.addNotes(inputMap, nickname);
				if (state) {
					isSuccess = true;
					info = "添加成功";
					map.put("isSuccess", isSuccess);
					map.put("info", info);
					OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
				}else{
					isSuccess = false;
					info = "添加失败";
					map.put("isSuccess", isSuccess);
					map.put("info", info);
					OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
				}
			}
		}
	}
	@RequestMapping("updateNotes")
	public void updateNotes(HttpServletRequest request,
			HttpServletResponse response){
		Map<String,Object> returnMap = new HashMap<String, Object>();
		Boolean isSuccess = true;
		String info = null;
		String nickname = SessionUtil.getStringAttri(request, SessionData.nameKey);
		if(StringUtils.isEmpty(nickname)){
			isSuccess = false;
			info = "请登录";
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}else{
			String courseId = request.getParameter("courseId");
			String listId = request.getParameter("listId");
			String content = request.getParameter("content");
			Map<String, Object> whereMap = new HashMap<String, Object>();
			whereMap.put("courseId", courseId);
			whereMap.put("listId", listId);
			whereMap.put("creater", nickname);
			Boolean state = courseStudyService.updateNotes(whereMap, content);
			if(state){
				isSuccess = true;
				info = "保存成功";
			}else{
				isSuccess = false;
				info = "保存失败";
			}
			returnMap.put("isSuccess", isSuccess);
			returnMap.put("info", info);
			OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
		}
	}
	@RequestMapping("getCon/{id}")
	public void getCon(HttpServletRequest request,HttpServletResponse response,
			@PathVariable Integer id){
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap = courseStudyService.getCon(id);
		OutputUtil.returnString(response, JSONSerielizer.toJson(returnMap, null, null));
	}
	@RequestMapping("readFile/{pptUrl}")
	public void readFile(HttpServletRequest request, HttpServletResponse response, 
			@PathVariable String pptUrl){
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		
		File file = new File(serverBuffer.toString() + pptUrl);
		ByteArrayOutputStream bos = null;
		BufferedInputStream in = null;
		OutputStream outputStream = null;
		try {
			bos = new ByteArrayOutputStream((int) file.length());
			in = new BufferedInputStream(new FileInputStream(file));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			byte[] data = bos.toByteArray();
			
			String fileName = "test";
			
			String realFileName = URLEncoder.encode(fileName, "UTF-8");
			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ realFileName + "\"");
			response.addHeader("Content-Length", "" + data.length);
			response.setContentType("application/octet-stream;charset=UTF-8");
			outputStream = new BufferedOutputStream(response.getOutputStream());
			outputStream.write(data);
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
			// isSuccess = false;
			// throw new FileReadException("文件读取发生错误");
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @param courseId
	 * @author HelloWorld_Luo
	 * @date 2017年3月7日
	 */
	@RequestMapping("getVidoPptRel/{courseId}")
	public void getVidoPptRel(HttpServletRequest request,HttpServletResponse response,
			@PathVariable Integer courseId){
		Map<String, Object> relMap = new HashMap<String, Object>();
		relMap = courseStudyService.getVidoPptRelation(courseId);
		OutputUtil.returnString(response, JSONSerielizer.toJson(relMap, null, null));
	}
	
}
